package com.aispeech.jarpc;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

@Slf4j
public class TextBin {
    private String param;
    private byte[] bin;

    public TextBin(String param, byte[] bin) {
        this.param = param;
        this.bin = bin;
    }

    public static TextBin from(byte[] bytes) {
        int jsonLength = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00) | ((bytes[2] << 24) >>> 8) | (bytes[3] << 24);
//        log.info("[ JsonBin.from ] bytes length: {}, json length: {}, int: {}", bytes.length, jsonLength, ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt());

        byte[] chars = new byte[jsonLength];

        int nextOffset = 4 + jsonLength;

        for (int i = 4; i < nextOffset; i++) {
            chars[i - 4] = bytes[i];
        }

        byte[] bin = Arrays.copyOfRange(bytes, nextOffset, bytes.length);
        return new TextBin(new String(chars), bin);
    }

    public String getParam() {
        return param;
    }

    public void setParam(String param) {
        this.param = param;
    }

    public byte[] getBin() {
        return bin;
    }

    public void setBin(byte[] bin) {
        this.bin = bin;
    }

    public ByteBuffer asBuffer() {
        byte[] bJson = param.getBytes();
        
        int length = 4+bJson.length;
        if (bin != null && bin.length > 0) {
        	length =  length + bin.length;
        }
        ByteBuffer buffer = ByteBuffer.allocate(length);

        buffer.order(ByteOrder.LITTLE_ENDIAN);
//        log.info("[ JsonBin.asBuffer ] param length: {}， param: {}", bJson.length, param);

        buffer.putInt(bJson.length);
        buffer.put(bJson);

        if (bin != null && bin.length > 0)
            buffer.put(bin);

        return buffer;
    }
}
